# -*- coding:utf-8 -*-
# coreseek3.2 python connect mongodb
# author: Bruce
# date: 2012-12-06 18:00

from os import path
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pymongo
import datetime
import pprint

pp = pprint.PrettyPrinter()

class MainSource(object):
    def __init__(self, conf):
        self.conf =  conf
        self.idx = 0
        self.data = []
        self.conn = None
        self.db = None

    def GetScheme(self):  #获取结构，docid、文本、整数
        return [
            ('id' , {'docid':True, } ),
            ('title', { 'type':'text'} ),
            ('author', { 'type':'text' }),
            ('tag', { 'type': 'text' }),
            ('content', { 'type':'text'}),
            ('time', {'type':'text'}),
            ('rel_link', {'type':'text'}),
        ]

    def GetFieldOrder(self): #字段的优先顺序
        return [('title', 'content')]
        
    def Connected(self):   #如果是数据库，则在此处做数据库连接
        if self.conn==None:       
            self.conn = pymongo.Connection('localhost', 27017)
            self.db = self.conn.news.news
            resultsets = self.db.find()
            #for item in resultsets:
            #   print item['id']
            #   print item['title']
            #   print item['author']
            #   print item['tag']
            #   print item['content']
            #   print item['time']
            #   print item['rel_link']
            self.data = [item for item in resultsets]
            #self.data = [{u'id': 1, u'title': u'阿达发达发射的发达', u'author': u'新浪新闻', u'content': u'阿拉善的积分拉卡的积分拉萨大开发', u'time': u'2012-07-30 15:29', u'rel_link': u'http://news.sina.cn/?sa=t124v2357d6534820&vt=4'}] 
               #push 
            #self.data = resultsets
        pass

    def NextDocument(self,err=''):   #取得每一个文档记录的调用
        if self.idx < len(self.data):
            item = self.data[self.idx]
            self.id = item['id'] #'docid':True
            self.title = item['title'].encode('utf-8')
            self.author = item['author'].encode('utf-8')
            self.tag = item['tag'].encode('utf-8')
            self.content = item['content'].encode('utf-8')
            self.time = item['time']
            self.time = item['rel_link']
            self.idx += 1
            return True
        else:
            return False
    
    def get_total_number_of_records():
        if self.conn==None:
            self.conn = pymongo.Connection('localhost', 27017)
            self.db = self.conn.news.news
            return self.db.count()
        pass

if __name__ == "__main__":    #直接访问演示部分
    conf = {}
    source = MainSource(conf)
    source.Connected()

    while source.NextDocument():
        print "id=%d, title=%s, content=%s" % (source.id, source.title, source.content)
    pass
#eof
